<template>
  <view class="chat-list-container" @click="handleCloseSwipeAction">
    <u-swipe-action
      v-for="(item, index) in friends"
      :key="item['friends_id']"
      :index="index"
      :show="item.show"
      :options="uSwipeActionOptions"
      disabled
      @open="handleOpenSwipeAction"
      @click.stop="handleClickSwipeAction"
    >
      <view class="item-friend" @click.stop="handleToChat(item)">
        <view class="face-friend" :style="{backgroundImage: `url(${item['face']})`}" />
        <view class="info-friend">
          <view class="name-friend">
            <text>{{ item['name'] }}</text>
            <text v-if="item['un_read_num'] > 0" class="unread-friend">
              {{ item['un_read_num'] > 99 ? '99+' : item['un_read_num'] }}
            </text>
          </view>
          <div class="desc-friend">
            <text>{{ messageDesc(item) }}</text>
          </div>
        </view>
      </view>
    </u-swipe-action>
    <view v-if="loading || !friends.length" class="loading-view">
      <u-loading v-if="loading" :size="43"></u-loading>
      <text style="margin-top: 10rpx;">{{ loading ? '加载中...' : '暂无数据' }}</text>
    </view>
  </view>
</template>

<script>
import ChatApi from './ChatApi'
import uSwipeAction from '../uview-ui/components/u-swipe-action/u-swipe-action'
import { api } from '../config/config'
import JSONBig from '../common/json-bigint'
import websocket from './Websocket'

export default {
  name: 'chat-list',
  components: { uSwipeAction },
  data() {
    return {
      chatApi: new ChatApi('buyer'),
      loading: true,
      friends: [],
      uSwipeActionOptions: [
        { text: '删除', style: { backgroundColor: '#dd524d' } }
      ]
    }
  },
  onShow() {
    if(!websocket.isOpen()) {
      this.chatApi.getWebsocketToken().then(res=>{
        websocket.init(api.im + '/im/ws?token=' + res)
      })
    }
    //处理websocket消息
    uni.$on('websocket-msg', this.handleSocketMessage)
    this.getFriends()
  },
  onHide() {
    uni.$off('websocket-msg', this.handleSocketMessage)
  },
  methods: {
    /**
     * 获取好友列表，轮询
     */
    getFriends() {
      this.chatApi.getFriends().then(res => {
        this.friends = res.map(item => {
          item.show = false
          return item
        })
        this.loading = false
      })
    },
    /**
     * 朋友最后一条消息预览
     * @param item
     * @returns {string}
     */
    messageDesc(item) {
      const message = item['message_list'][0]
      if (!message) return ''
      if (message['type'] === 'IMAGES') return '[图片]'
      if (message['type'] === 'VIDEO') return '[视频]'
      if (message['type'] !== 'TEXT') return '[链接]'
      return message['text'].replace(/<img.+>/g, '[表情]').replace(/\n|&nbsp;/g, '')
    },
    /**
     * 去聊天界面
     * @param item
     */
    handleToChat(item) {
      let url = '/chat-module/chat'
      url += `?receiver_id=${item['friends_id']}`
      url += `&receiver_name=${encodeURIComponent(item['name'])}`
      uni.navigateTo({ url })
    },
    /**
     * 打开了swipe
     * @param index
     */
    handleOpenSwipeAction(index) {
      this.friends[index].show = true
      this.friends.map((val, idx) => {
        if(index !== idx) this.list[idx].show = false
      })
    },
    /**
     * 点击了swipe
     * @param index
     * @param index1
     */
    handleClickSwipeAction(index, index1) {
      // TODO: 待后端API
      console.log(index, index1)
    },
    /**
     * 点击空白处关闭swipe
     */
    handleCloseSwipeAction() {
      this.friends = this.friends.map(item => {
        item.show = false
        return item
      })

    },
    /**
     * 处理socket消息
     */
    handleSocketMessage(message) {
      let msg = JSONBig.parse(message)

      if (msg.type === 'friend') {
        this.getFriends()
      }
      if (msg.type === 'msg') {
        if (typeof msg.payload !== 'object') return
        const sender_id = msg.sender_id
        const index = this.friends.findIndex(item => Number(item.friends_id) === Number(sender_id))
        if (index === -1) return
        const friend = this.friends[index]
        friend.un_read_num += 1
        friend.message_list.splice(0, 0, msg.payload)
        const friends = this.friends
        friends.splice(index, 1, friend)
        this.friends = friends
      }
    }
  },
  onUnload() {
  }
}
</script>

<style lang="scss" scoped>
.chat-list-container {
  min-height: 100%;
  padding-bottom: 0;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  box-sizing: border-box;
}
.item-friend {
  display: flex;
  align-items: center;
  width: 100%;
  height: 148rpx;
  padding-left: 36rpx;
  box-sizing: border-box;
  background-color: #ffffff;
  overflow: hidden;
  &:last-child {
    border-bottom-left-radius: 30rpx;
    border-bottom-right-radius: 30rpx;
    .info-friend::after {
      content: none;
    }
  }
  .face-friend {
    flex-shrink: 0;
    width: 90rpx;
    height: 90rpx;
    border-radius: 90rpx;
    background-size: cover;
    background-repeat: no-repeat;
  }
  .info-friend {
    flex: 1;
    position: relative;
    height: 100%;
    padding-right: 36rpx;
    box-sizing: border-box;
    margin-left: 24rpx;
    padding-top: 38rpx;
    &::after {
      content: '';
      position: absolute;
      left: -50%;
      bottom: 0;
      width: 200%;
      height: 2rpx;
      background-color: #ecedec;
      transform: scale(0.5);
    }
  }
  .name-friend {
    position: relative;
    font-size: 32rpx;
    color: #242524;
    .unread-friend {
      display: flex;
      justify-content: center;
      align-items: center;
      position: absolute;
      color: #ffffff;
      font-size: 24rpx;
      font-weight: bold;
      background-color: red;
      top: 0;
      right: 0;
      padding: 2rpx 10rpx;
      min-width: 50rpx;
      border-radius: 25rpx;
    }
  }
  .desc-friend {
    font-size: 26rpx;
    margin-top: 22rpx;
    width: 480rpx;
    height: 26rpx;
    line-height: 26rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    color: #989999;
  }
}
.loading-view {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: calc(100vh - 120rpx);
}
</style>
